package api345

import (
	"duoke/model"
	"duoke/utils/yaml"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
)

type Config struct {
	Key string
}

func NewConfig() *Config {
	config := yaml.GetConfig()
	return &Config{
		Key: config.Api345.Key,
	}
}

type Respone struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		Title string      `json:"title"`
		Image string      `json:"image"`
		Video string      `json:"video"`
		Url   string      `json:"url"`
		Alais interface{} `json:"alais"`
	} `json:"data"`
	ExecTime float64 `json:"exec_time"`
	UserIp   string  `json:"user_ip"`
}

// 视频解析
func (c *Config) Jiexi(content string) (*Respone, error) {
	baseURL := "https://www.345api.cn/api/jiexi/get"
	params := url.Values{}
	params.Add("key", c.Key)
	params.Add("url", content)
	send, err := c.Send(params, baseURL)
	if err != nil {
		return nil, err
	}
	var respone Respone
	err = json.Unmarshal(send, &respone)
	if respone.Code != 200 {
		return nil, errors.New(respone.Msg)
	}
	if err != nil {
		return nil, err
	}
	return &respone, nil
}

// 查询ip
func (c *Config) Query(ip string) (*Respone, error) {
	baseURL := "https://www.345api.cn/api/ipv2/query"
	params := url.Values{}
	params.Add("key", c.Key)
	params.Add("ip", ip)
	send, err := c.Send(params, baseURL)
	if err != nil {
		return nil, err
	}
	var respone Respone
	err = json.Unmarshal(send, &respone)
	if err != nil {
		return nil, err
	}
	return &respone, nil
}

// 根据ip获取地址
func (c *Config) GetAddr(ip string) (*model.Map, error) {
	config := yaml.GetConfig()
	baseURL := "https://apis.map.qq.com/ws/location/v1/ip"
	params := url.Values{}
	params.Add("ip", ip)
	params.Add("key", config.TencentCloud.MapKey)
	send, err := c.Send(params, baseURL)
	if err != nil {
		return nil, err
	}
	var respone model.Map
	err = json.Unmarshal(send, &respone)
	if err != nil {
		return nil, err
	}
	return &respone, nil
}

func (c *Config) Send(params url.Values, baseURL string) ([]byte, error) {
	fullURL := baseURL
	if params.Encode() != "" {
		fullURL += "?" + params.Encode()
	}
	req, err := http.NewRequest("GET", fullURL, nil)
	if err != nil {
		return nil, err
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	result, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)
	return result, nil
}
